from typing import Literal

import UnityPy

from utils.创建文件夹 import createFolder

path_id_map = {"en": {}, "jp": {}}

lang_map = {"ja-jp": "jp", "en-us": "en"}
obj_name_list = [
    "card_indx",
    "card_name",
    "card_desc",
    "card_part",  # 这两玩意是卡片做了一个拆
    "card_pidx",
]


def gen_path_id_map(env: any):
    if len(path_id_map["en"]):
        return
    for obj in env.objects:
        if obj.type.name == "ResourceManager":
            rm = obj.read()
            for container, ptr in rm.m_Container.items():
                try:
                    data = ptr.read()
                    path_id = data.path_id
                    if len(container.split("/")[-2:]) < 2:
                        continue
                    _lang, _obj_name = container.split("/")[-2:]
                    if _lang in list(lang_map.keys()) and _obj_name in obj_name_list:
                        path_id_map[lang_map[_lang]][path_id] = (
                            _obj_name.split("_")[0].upper()
                            + "_"
                            + _obj_name.split("_")[1].capitalize()
                        )
                except Exception:
                    ...
            break


def extract_file(src: str, dst: str, lang: Literal["en", "jp"]):
    env = UnityPy.load(src)
    gen_path_id_map(env)
    print(path_id_map)
    for obj in env.objects:
        if obj.type.name == "TextAsset" and obj.path_id in path_id_map[lang].keys():
            data = obj.read()
            obj_name: str = path_id_map[lang][obj.path_id]
            print(data.name)
            with open(f"{dst}/{lang}/{obj_name}", "wb") as f:
                f.write(bytes(data.script))


createFolder("output/1_res/en")
createFolder("output/1_res/jp")

extract_file("data/data.unity3d", "output/1_res", "en")
extract_file("data/data.unity3d", "output/1_res", "jp")
